from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from goods.models import SKU
from .serializers import OrderSettlementSerializer,OrderCommitSerializer
from decimal import Decimal
from rest_framework.generics import CreateAPIView
"""
订单结算
1, 当前端在购物车页面点击去结算的时候
2, 取出redis中的,选中的商品,结算
3, 返回对应的结果

"""
class OrderSettlementView(APIView):

    permission_classes = [IsAuthenticated]

    def get(self,request):

        #0,获取用户对象
        user = request.user

        #1,获取redis中的数据
        redis_conn = get_redis_connection("cart")
        redis_cart = redis_conn.hgetall("cart_%s"%user.id)
        redis_cart_selected = redis_conn.smembers("cart_selected_%s"%user.id)

        #2,通过商品编号,取出商品对象
        sku_list = []
        for sku_id in redis_cart_selected:
            #2,1取出商品对象
            sku = SKU.objects.get(id=sku_id)

            #2,2设置商品数量
            sku.count = redis_cart[sku_id]

            #2,3,添加到列表中
            sku_list.append(sku)

        #3,创建序列化器,转换数据格式
        data = {
            "freight":Decimal("10.0"),
            "skus":sku_list
        }
        serializer =  OrderSettlementSerializer(data)
        return Response(serializer.data)


"""
提交订单(生成订单)
1, 当前端点击提交订单的时候
2, 携带参数
3, 校验参数,创建order订单,和ordergoods数据
"""
class OrderCommitView(CreateAPIView):

    permission_classes = [IsAuthenticated]
    serializer_class = OrderCommitSerializer
